
const { getProperty,assert  } = require('../../lib/tools')
const {writeFileSync,existsSync,mkdirSync} = require('fs')
const { dirname } = require('path')
const { renderFile } = require('../../lib/swig-template')


/**
 * 将writeOutTheArea中的内容写出去
 * 必填参数：
 * template
 * dist
 * format
 * 
 * @param {上下文} param0 
 * @returns 
 */
module.exports = function({writeOutTheArea,config:{dicts}}){
    if(!writeOutTheArea){
        return
    }
    const formats = getProperty(dicts,d=>d.formats.formats)
    writeOutTheArea.forEach(content => {
        try {
            // 确定前端页面的模板
            const template = getProperty(content,c => c.template, undefined)
            assert(template,"模板配置错误!")

            const distPath =  getProperty(content,c => c.dist, undefined)
            assert(distPath,"目标文件配置错误!")

            const distDir = dirname(distPath)
            if(!existsSync(distDir)){
                mkdirSync(distDir,{recursive:true})
            }

            // 生成内容并写入目标位置
            const genContent = renderFile(template, content)
            // format类型
            const formatOption = getProperty(content, c=> formats[c.format])
            // writeFileSync(distPath+".bak",genContent.replace(/^\s*\n/mg,""),{encoding:'utf-8'})

            if(formatOption){
                const { format } = require('prettier')
                format(genContent,formatOption).then(fileContent =>{
                    writeFileSync(distPath,fileContent.replace(/^\s*\n/mg,""),{encoding:'utf-8'})
                    console.log(`write format success: ${distPath}`)
                })
            }else{
                writeFileSync(distPath,genContent.replace(/^\s*\n/mg,""),{encoding:'utf-8'})
                console.log(`write not format success: ${distPath}`)
            }
           
            
        } catch (error) {
            
            console.log(error)
        }



    })
    
}